from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from image_helper import *
from selenium.webdriver import ActionChains

browser = webdriver.Chrome()
# 设置浏览器窗口大小
browser.set_window_size(1400, 700)
# 设置隐式等待对象
wait = WebDriverWait(browser, 5)

def is_pixel_equal(image1, image2, x, y):
    '''判断对应像素颜色是否相同的方法'''
    p1 = image1.load()[x, y]
    p2 = image2.load()[x, y]
    # 判断用的阈值，颜色差值<60我们认为这两个基本一样
    value = 80
    if abs(p1[0] - p2[0]) < value and abs(p1[1] - p2[1]) < value and abs(p1[2] - p2[2]) < value:
        return True
    return False

# 获取缺口位置坐标
def get_gap_position(image1,image2):
    '''获取图片缺口'''
    left = 75
    size = image1.size
    # 先横向在纵向扫描像素匹配颜色是否相等
    for x in range(left, size[0]):
        for y in range(size[1]):
            pixel_equal = is_pixel_equal(image1,image2, x, y)
            if not pixel_equal:
                return x
    return -1

def get_page():
    url = 'https://passport.bilibili.com/login'
    browser.get(url)

    # 输入手机号和密码
    input_mobile = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#login-username')))
    input_mobile.clear()
    input_mobile.send_keys('15335668845')

    input_password = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#login-passwd')))
    input_password.clear()
    input_password.send_keys('12345678A')

    ok_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a.btn.btn-login')))
    ok_button.click()

    # 延时等验证图片出来再截图
    time.sleep(2)
    image1 = crop_image(browser, '.geetest_canvas_slice.geetest_absolute', 'a1.png')

    # 修改css属性，让隐藏的图片显示出来
    str_js = 'var element = document.getElementsByClassName("geetest_canvas_fullbg geetest_fade geetest_absolute")[0];element.style.display="block";'
    browser.execute_script(str_js)
    time.sleep(1)
    image2 = crop_image(browser, '.geetest_canvas_slice.geetest_absolute', 'a2.png')

#     获取缺口位置
    x = get_gap_position(image1, image2)
    print(x)

    # 获取移动轨迹
    gap_length = x - 19
    move_list = get_track(gap_length)
    print(move_list)
    slider_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.geetest_slider_button')))
    ActionChains(browser).click_and_hold(slider_button).perform()
    # 进行一步步的位移
    for distance in move_list:
        ActionChains(browser).move_by_offset(xoffset=distance,yoffset=0).perform()
    time.sleep(1)
    # 松开按钮
    ActionChains(browser).release().perform()
# 获取移动速度轨迹
def get_track(distance):
    """
    根据偏移量获取移动轨迹
    :param distance: 偏移量
    :return: 移动轨迹
    """
    track = []  # 移动轨迹
    current = 0  # 当前位移
    mid = distance * 3 / 5  # 减速阀值
    t = 0.7  # 计算间隔
    v = 0  # 初速度
    distance += 14  # 滑超过一段距离
    while current < distance:
        if current < mid:
            a = 4  # 加速度为正
        else:
            a = -2  # 加速度为负
        v0 = v  # 初速度v0
        v = v0 + a * t  # 当前速度v
        move = v0 * t + 1 / 2 * a * t * t  # 移动距离 move
        current += move  # 当前位移
        track.append(round(move))
        # print(track)
    track[-1] = distance - sum(track[:-1])
    return track

def main():
    get_page()

if __name__ == '__main__':
    main()